import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

// 观看记录项接口
export interface WatchHistoryItem {
  id: string | number
  title: string
  description?: string
  playUrl?: string
  cover?: string
  author: {
    name: string
    icon?: string
  }
  duration?: number
  watchedDuration?: number // 已观看时长（秒）
  watchedAt: number // 观看时间戳
  tags?: Array<{ name: string }>
  consumption?: {
    collectionCount?: number
    realCollectionCount?: number
    replyCount?: number
    shareCount?: number
  }
}

const STORAGE_KEY = 'watch_history'
const MAX_HISTORY_COUNT = 10

export const useWatchHistoryStore = defineStore('watchHistory', () => {
  // 观看记录数组
  const historyList = ref<WatchHistoryItem[]>([])

  // 从本地存储加载数据
  const loadFromStorage = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        historyList.value = JSON.parse(stored)
      }
    } catch (error) {
      console.error('加载观看记录失败:', error)
      historyList.value = []
    }
  }

  // 保存到本地存储
  const saveToStorage = () => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(historyList.value))
    } catch (error) {
      console.error('保存观看记录失败:', error)
    }
  }

  // 添加观看记录
  const addHistory = (video: any) => {
    if (!video || !video.id) return

    // 检查是否已存在，如果存在则先移除
    const existingIndex = historyList.value.findIndex(item => item.id === video.id)
    if (existingIndex !== -1) {
      historyList.value.splice(existingIndex, 1)
    }

    // 获取封面图片
    let coverUrl = ''
    if (typeof video.cover === 'string') {
      coverUrl = video.cover
    } else if (video.cover) {
      coverUrl = video.cover.feed || video.cover.detail || video.cover.blurred || ''
    }

    // 构建观看记录项
    const historyItem: WatchHistoryItem = {
      id: video.id,
      title: video.title || '',
      description: video.description,
      playUrl: video.playUrl,
      cover: coverUrl,
      author: {
        name: video.author?.name || '未知',
        icon: video.author?.icon
      },
      duration: video.duration || 0,
      watchedDuration: video.watchedDuration || 0,
      watchedAt: Date.now(),
      tags: video.tags,
      consumption: video.consumption
    }

    // 添加到数组最前面
    historyList.value.unshift(historyItem)

    // 如果超过最大数量，删除最后一项
    if (historyList.value.length > MAX_HISTORY_COUNT) {
      historyList.value = historyList.value.slice(0, MAX_HISTORY_COUNT)
    }

    // 自动保存到本地存储
    saveToStorage()
  }

  // 更新观看进度
  const updateWatchProgress = (videoId: string | number, watchedDuration: number) => {
    const item = historyList.value.find(item => item.id === videoId)
    if (item) {
      item.watchedDuration = watchedDuration
      saveToStorage()
    }
  }

  // 删除观看记录
  const removeHistory = (videoId: string | number) => {
    const index = historyList.value.findIndex(item => item.id === videoId)
    if (index !== -1) {
      historyList.value.splice(index, 1)
      saveToStorage()
    }
  }

  // 清空观看记录
  const clearHistory = () => {
    historyList.value = []
    localStorage.removeItem(STORAGE_KEY)
  }

  // 初始化：从本地存储加载
  loadFromStorage()

  return {
    historyList,
    addHistory,
    updateWatchProgress,
    removeHistory,
    clearHistory,
    loadFromStorage
  }
})

